package com.my.blogapi.commo.aop;

import com.alibaba.fastjson.JSON;
import com.my.blogapi.utils.HttpContextUtils;
import com.my.blogapi.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class LogAdvice {

    //定义切点
    @Pointcut("@annotation(com.my.blogapi.commo.aop.LogAspect)")
    public void pt(){}

    //定义通知--环绕

    @Around("pt()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {

        Long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        Long end = System.currentTimeMillis();
        logAdice(joinPoint,(end-start));
        return result;
    }

    private void logAdice(ProceedingJoinPoint joinPoint, long time) {
        //获取反射对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取执行的方法对象
        Method method = signature.getMethod();
        //获取增强方法上的注解对象
        LogAspect logAnnotation = method.getAnnotation(LogAspect.class);
        log.info("=====================log start================================");
        //读取的都是注解上的内容
        log.info("module:{}",logAnnotation.module());
        log.info("operation:{}",logAnnotation.operation());
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("request method:{}",className + "." + methodName + "()");

//        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params = JSON.toJSONString(args[0]);
        log.info("params:{}",params);
        //获取request 设置IP地址
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        log.info("ip:{}", IpUtils.getIpAddr(request));


        log.info("excute time : {} ms",time);
        log.info("=====================log end================================");
    }
}
